﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Security;
using RLAWEB.RLAServiceReference;

namespace RLAWEB.Models
{
    public class Helper
    {
        /// <summary>
        /// Find user ID from a provided cookie.
        /// </summary>
        /// <param name="authCookie">Input should be Request.Cookies[FormsAuthentication.FormsCookieName] </param>
        /// <returns></returns>
        public static User GetLoggedInUser(HttpCookie authCookie)
        {
            int id = -1;
            if (authCookie != null)
            {

                var ticket = FormsAuthentication.Decrypt(authCookie.Value);


                if (int.TryParse(ticket.UserData, out id))
                {
                    if (id > 0)
                    {
                        var client = new RLAServiceReference.RealLifeServiceClient();
                        return client.GetUserById(id);
                    }
                    else
                    {
                        throw new Exception("Id not valid.");
                    }
                }
                else
                {
                    throw new Exception("User data corrupt.");
                   
                }
            }
            else
            {
                throw new Exception("Authcookie not found");
            }
            
        }

    }
}